<template>
  <div class="cg-gird-item" :style="girdItemStyle" :id="girdItemId">
    <slot></slot>
  </div>
</template>
<script setup lang="ts">
import _ from 'lodash'
import { ref, onMounted, onUnmounted, computed, getCurrentInstance } from 'vue'
import Emitter from '../../tools/emitter'

// 定义组件名称
defineOptions({
  name: 'cg-gird-item'
})

// 定义props
const props = withDefaults(
  defineProps<{
    label: string | undefined
  }>(),
  {
    label: undefined
  }
)

// 响应式数据
const girdItemId = ref<string | undefined>(undefined)
const girdItemStyle = ref<Record<string, string>>({})
const girdItemWidth = ref<number>(0)
let seedId = 0

// 获取当前组件实例
const instance = getCurrentInstance()

// 手动实现findParent功能，替代原mixin中的方法
function findParent(componentName: string) {
  let current = instance?.parent
  while (current) {
    if (current.type.name === componentName) {
      return current
    }
    current = current.parent
  }
  return null
}

// 计算属性 - 查找父组件
const parent = computed(() => {
  return findParent('CGGird')
})

// 响应式数据 - 遗漏的itemList
const itemList = ref<any[]>([])

// 查找列索引
function findColIndex() {
  if (instance?.vnode.el instanceof Element) {
    const children = _.get(instance.vnode.el, 'parentNode.children')
    if (children instanceof HTMLCollection) {
      return Array.from(children).findIndex((item) => item === instance.vnode.el)
    }
  }
  return -1
}

// 更新网格项样式
function updateGirdItemStyle() {
  const parentComp = parent.value
  if (parentComp) {
    const { columnConfig, width, shape } = parentComp
    const index = findColIndex()
    let { colNum, maxWidth, gutter } = columnConfig
    if (maxWidth >= 0) {
      let minColNum = width / maxWidth
      colNum = Math.max(colNum, minColNum)
    }
    let colWidth = (width - gutter * (colNum - 1)) / colNum
    girdItemWidth.value = Math.floor(colWidth * 10) / 10
    let style: Record<string, string> = {
      width: girdItemWidth.value + 'px',
      marginLeft: index % colNum > 0 ? gutter + 'px' : '0px',
      marginTop: Math.floor(index / colNum) > 0 ? gutter + 'px' : '0px'
    }
    if (shape === 'rectangle') {
      style['height'] = girdItemWidth.value + 'px'
    }
    girdItemStyle.value = style
    return
  }
  girdItemStyle.value = {}
}

// 生命周期钩子
onMounted(() => {
  girdItemId.value = 'gird-item-' + seedId++
  const parentComp = parent.value
  if (parentComp) {
    // 传递当前组件实例给父组件
    parentComp.addItem(instance)
  }
})

onUnmounted(() => {
  const parentComp = parent.value
  if (parentComp) {
    parentComp.removeItem(instance)
  }
})

// 暴露方法给父组件
defineExpose({
  updateGirdItemStyle,
  girdItemId
})
</script>
